/*
 * @Author: zhang zhijiang 2824735304@qq.com
 * @Date: 2025-04-21 20:26:09
 * @LastEditors: zhang zhijiang 2824735304@qq.com
 * @LastEditTime: 2025-04-22 21:07:31
 * @FilePath: /linux/test_4_21/tcpclient.cc
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include <iostream>
#include <iostream>
#include <string>
#include <cstring>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <strings.h>
#include <arpa/inet.h>
#include <memory>
#include <unistd.h>
#include <vector>
#include <functional>
#include <unordered_map>
using namespace std;
//./tcpclient "ip" "port"
void usage(string proc)
{
    cout << "right usage :" << proc << "IP" << "[1024+]" << "port" << endl;
}
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        usage(argv[0]);
        exit(2);
    }
    uint16_t serverport = stoi(argv[2]);
    string serverip = argv[1];
    struct sockaddr_in server;
    inet_pton(AF_INET, argv[1], &(server.sin_addr));
    server.sin_port = htons(serverport);
    server.sin_family = AF_INET;
    socklen_t len = sizeof(server);
    while (true)
    {
        int cnt = 5;
        bool reconnect = false;
 
        int sockfd = 0;
        do
        {
            sockfd = socket(AF_INET, SOCK_STREAM, 0);
            if (sockfd < 0)
            {
                cout<<"socket error"<<endl;
                return 1;
            }
            int n = connect(sockfd, (sockaddr *)&server, len);
            if (n < 0)
            {
                reconnect = true;
                cnt--;
                cout << "is connecting " << cnt << "..." << endl;
                sleep(1);
            }
            if (n == 0)
            {
                reconnect = false;
            }
        } while (reconnect && cnt);

        string message;
        while (true)
        {
            getline(cin, message);
            int z = write(sockfd, message.c_str(), sizeof(message));
            if (z < 0) // 写入失败，进行重连
            {
                reconnect = true;
                break;
            }
            char buffer[4096];
            int m = read(sockfd, buffer, sizeof(buffer));
            if (m <= 0) // 读取失败，进行重连
            {
                reconnect = true;
                break;
            }
            buffer[m] = 0;
            cout << "get a message from server" << buffer << endl;
        }
        close(sockfd);
    }

    return 0;
}